package com.example.finalcameraproject.service;


import com.example.finalcameraproject.model.Camera;
import com.example.finalcameraproject.repository.CameraRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CameraServiceImpl implements CameraService{

    @Autowired
    private CameraRepository cameraRepository;
    @Override
    public List<Camera> getAllCamera() {
        return cameraRepository.findAll();
    }

    @Override
    public void saveCamera(Camera camera) {
        this.cameraRepository.save(camera);
    }

    @Override
    public Camera getCameraById(long id) {
        //调用数据访问层查找指定ID的相机，返回Optional对象
        Optional< Camera > optional = cameraRepository.findById(id);

        Camera camera = null;
        //如果存在指定id的相机
        if (optional.isPresent()) {
            //从Optional对象中获取员工对象
            camera = optional.get();
        } else {
            //否则抛出运行时异常
            throw new RuntimeException(" 找不到相机ID :: " + id);
        }
        return camera;

    }
    @Override
    public void deleteCameraById(long id) {
        this.cameraRepository.deleteById(id);
    }

    //分页、排序与搜索
    @Override
    public Page<Camera> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection, String CameraState) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();
        // 判断相机状态是否为空，为空则设置默认值为""
        CameraState = CameraState != null ? CameraState : "";
        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        // 执行模糊查询并应用分页和排序参数
        Page<Camera> cameraPage = cameraRepository.findByStateContainingIgnoreCase(CameraState, pageable);
        // 包含分页的数据列表
        return cameraPage;
    }
}
